class Checkout < ActiveRecord::Base

  belongs_to :user
  belongs_to :cart
  belongs_to :address, :class_name => 'Checkout::Address'
  belongs_to :contact, :class_name => 'Checkout::Contact'

  @@payment_types = {
    :creditcard => 1,
    :account    => 2
  }

  attr_accessor :payment


  # Maak een Checkout::Payment-model aan.
  def after_initialize
    @payment = case read_attribute(:payment_type)
      
      when @@payment_types[:creditcard] 
        then Checkout::Payment::Creditcard.find(read_attribute(:payment_id))

      when @@payment_types[:account]    
        then Checkout::Payment::Account.new(user) unless user == nil

      else 
        nil
    end
  end


  # Stel de payment_type in.
  def before_save
    if @payment.instance_of?(Checkout::Payment::Creditcard)
      write_attribute(:payment_type, @@payment_types[:creditcard])
      write_attribute(:payment_id, @payment.id)
    elsif @payment.instance_of?(Checkout::Payment::Account)
      write_attribute(:payment_type, @@payment_types[:account])
    else
      write_attribute(:payment_type, 0)
    end
  end


  # Betaal de bestelling.
  def execute_payment
    if @payment != nil
      return @payment.execute(total_cost)
    else
      raise Checkout::Payment::PaymentFailedException.new('Invalid payment type', 0)
    end
  end


  # Is de bestelling betaald?
  def paid?
    @payment.paid?
  end


  # Bereken de totale kosten van de bestelling.
  def total_cost
    cart.total_cost + shipping_cost
  end


  # Geef de verzendkosten.
  def shipping_cost
    return 2.5
  end


  #
  def ready?
    self.contact != nil and self.address != nil and self.payment != nil
  end

end